package com.itmayiedu.api.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @description: 模拟Ribbon的本地负载均衡，实现订单服务调用会员服务接口
 * @author: liucancan
 * @create: 2018-11-03 17:54
 **/
@RestController
public class ExtRibbonController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    // 请求次数
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    /**
     * 订单服务调用会员服务
     *
     * @return
     */
    @RequestMapping("/getMember")
    public String getMember() {
        int reqCount = atomicInteger.addAndGet(1);
        // 从注册中心中获取会员服务集群地址
        List<ServiceInstance> instances = discoveryClient.getInstances("app-itmayiedu-member");
        if (null != instances && instances.size() > 0) {
            ServiceInstance serviceInstance = instances.get(reqCount % instances.size());
            return serviceInstance.getUri() + " " + restTemplate.getForObject(serviceInstance.getUri() + "/getMember", String.class);
        }
        return "请求失败";
    }
}
